/*
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is the FxStruts MailReader Application.
 *
 * The Initial Developer of the Original Code is
 * Anirudh Sasikumar (http://anirudhs.chaosnet.org/).
 * Portions created by the Initial Developer are Copyright (C) 2008
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
*/

package com.adobe.mailreader.command
{
    import com.adobe.cairngorm.commands.ICommand;
    import com.adobe.cairngorm.control.CairngormEvent;
    import com.adobe.mailreader.business.SubscriptionCreateEditDelegate;
    import com.adobe.mailreader.events.SubscriptionCreateEditEvent;
    import com.adobe.mailreader.model.MailModelLocator;
    import com.adobe.mailreader.vo.SubscriptionVO;
    
    import flash.utils.ByteArray;
    
    import mx.controls.Alert;
    import mx.rpc.IResponder;
    import mx.rpc.events.FaultEvent;
    
    /* Subscription create / edit / delete support */
    public class SubscriptionCreateEditCommand implements ICommand, IResponder
    {
    	private var voData:SubscriptionVO;
    	private var evtType:String;
    	private var actionState:Boolean = false;    	
        
        public function SubscriptionCreateEditCommand()
        {
            
        }
               
        public function execute( event:CairngormEvent ):void
        {
            var userEvt:SubscriptionCreateEditEvent = event as SubscriptionCreateEditEvent;
            var subDelegate:SubscriptionCreateEditDelegate = new SubscriptionCreateEditDelegate(this);

            /* Save the action details and get the token for the operation. */
            if ( userEvt.subscriptionData != null )
            {
                voData = userEvt.subscriptionData;
                evtType = userEvt.type;
                var opStr:String = "Edit";
                
                switch ( userEvt.type )
                {
                    case SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE:
                        
                        opStr = "Create";
                        break;
                        
                    case SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE:
                        
                        opStr = "Delete";
                        break;
                        
                    case SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT:
                        
                        opStr = "Edit";
                        break;
                        
                }
                subDelegate.confirmSubscription(voData.host,
                                                opStr	            		
                                                );
                
            }
            else
            {
                Alert.show("Null evt passed to account create / edit command");
            } 	              
        }
        
        public function result( event : Object ) : void
        {				
            trace("Got result " + event.result);
            var model : MailModelLocator = MailModelLocator.getInstance();
            
            
            /* check if we got our token */
            if ( !actionState )
            {
                if ( event.result is Object && event.result.hasOwnProperty("result") && 
                     event.result.hasOwnProperty("org.apache.struts.taglib.html.TOKEN")  )
                {
                    /* save token, perform the actual operation */
                    model.transactionToken = event.result["org.apache.struts.taglib.html.TOKEN"];
                    performAction(new SubscriptionCreateEditDelegate(this), voData);
                    actionState = true;
                    return;
                }
                else
                {
                	performAction(new SubscriptionCreateEditDelegate(this), voData);
                    actionState = true;
                    return;
                }               
            } 

            /* check for errors from errors=true of fx:write and
             * return if any */
            if ( event.result is Object && event.result.hasOwnProperty("errors") )
            {
                /* dispatch appropriate failure notification */
                if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_CREATE_FAILED, event.result.errors);
                }
                else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_DELETE_FAILED, event.result.errors);
                }
                else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_EDIT_FAILED, event.result.errors);
                }
            }
            else if ( event.result is Object && event.result.hasOwnProperty("result") && event.result.result == "true" 
                        )
            {
                /* save token, dispatch success */
                if ( event.result.hasOwnProperty("org.apache.struts.taglib.html.TOKEN") )
                	model.transactionToken = event.result["org.apache.struts.taglib.html.TOKEN"];
                if ( event.result.result == "true" )
                {
                    if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE )
                    {
                        model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_CREATE_SUCCESS);
                    }
                    else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE )
                    {
                        model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_DELETE_SUCCESS);
                    }
                    else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT )
                    {
                        model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_EDIT_SUCCESS);
                    }
                }
                
            }
            else if ( event.result is String && event.result == "true" )
            {
            	if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_CREATE_SUCCESS);
                }
                else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_DELETE_SUCCESS);
                }
                else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_EDIT_SUCCESS);
                }
            }
            else
            {
                /* dispatch appropriate failure notification */
                if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_CREATE_FAILED);
                }
                else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_DELETE_FAILED);
                }
                else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT )
                {
                    model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_EDIT_FAILED);
                }
                
            }	
        }
        
        public function fault( event : Object ) : void
        {
            trace("Got fault" + event);
            var str:String = "";
            var model : MailModelLocator = MailModelLocator.getInstance();
            var faultEvent:FaultEvent = event as FaultEvent;
            if ( faultEvent )
            {
                if ( faultEvent.fault.faultCode == "Client.CouldNotDecode" )
                {
                    str = (faultEvent.message.body as ByteArray).toString();
                    model.notifyView(MailModelLocator.VIEW_ACCOUNT_EDIT_FAILED, str);
                    /* if we got html instead of AMF, this would be useful */
                    Alert.show("Str err: " + str);
                    return;
                }
            }

            /* dispatch appropriate failure notification */
            if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE )
            {
                model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_CREATE_FAILED, event.fault.faultString);
            }
            else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE )
            {
                model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_DELETE_FAILED, event.fault.faultString);
            }
            else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT )
            {
                model.notifyView(MailModelLocator.VIEW_SUBSCRIPTION_EDIT_FAILED, event.fault.faultString);
            }
        }

        /* Perform the actual create / edit / delete operation */
        private function performAction(subDelegate:SubscriptionCreateEditDelegate, vo:SubscriptionVO):void
        {
            if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_EDIT )
            {      	            	 
                subDelegate.editSubscription(voData.host,
                                             voData.autoConnect,
                                             voData.username,
                                             voData.password,
                                             voData.type,
                                             voData.token	            		
                                             );
            }
            else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_CREATE )
            {
                subDelegate.createSubscription(voData.host,
                                               voData.autoConnect,
                                               voData.username,
                                               voData.password,
                                               voData.type,
                                               voData.token	            		
                                               );
            }
            else if ( evtType == SubscriptionCreateEditEvent.EVENT_SUBSCRIPTION_DELETE )
            {
                subDelegate.deleteSubscription(voData.host,
                                               voData.autoConnect,
                                               voData.username,
                                               voData.password,
                                               voData.type,
                                               voData.token	            		
                                               );
            }
        }

        
    }
}